<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\BaseController;
use App\Models\User;
use Illuminate\Http\Request;
use App\SMS\SendTemplateSMS;
use App\SMS\M3Result;
use App\SMS\CCPRestSDK;
use Hash;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class FhoneController extends BaseController
{


    // 发送手机验证码
    public function sendcode(Request $request){
        //获取要发送的手机号
        $phone = $request->phone;
        if (!User::where('phone',$phone)){
            return  $this->response->errorBadRequest('此手机号没有绑定任何账号');
        }
        // 2.生成验证码
        $code = rand(1000,9999);
        $arr = [$code,5];

        // 调用容联云通讯的接口
        $templateSMS = new SendTemplateSMS();
        $M3result = new M3Result();

        $M3result = $templateSMS->sendTemplateSMS($phone,$arr,1);

        // 将验证码存入session
        Cache::put($phone.'code',$code,now()->addMinute(5));
        // 给客户端返回容联云通讯的结果
        return $M3result->toJson();
    }
    public function checkcode(Request $request){
        $request->validate([
           'phone' => 'required',
            'code' =>'required'
        ]);
        $code = Cache::get($request->phone.'code');
        if ( $code != $request->code){
            return $this->response->errorBadRequest('手机或者验证码不正确');
        }
        $e=User::where('phone',$request->phone)->get()->toArray();
        foreach ($e as $item) {
            $email = $item['email'];
            $password = $item['password'];
        }
        $credentials = [
            'email'=>$email,
            'password'=>$password
        ];
        $token = auth('api')->attempt($credentials);
        return $this->respondWithToken($token);
    }

    protected function respondWithToken($token)
    {
        return response()->json([    //$this->>response->array()'access_token' => $token,'token_type' => 'Bearer','expires_in' => auth('api')->factory()->getTTL() * 60])
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

}
